// $Id: loggerrequestfailpopularity.cpp 71 2004-11-23 14:36:02Z hansemil $
#include "loggerrequestfailpopularity.h"
#include "loghandler.h"
#include "node.h"
#include "noderequestfileparameters.h"
#include "distributions.h"
#include <iostream>
#include <list>
#include <vector>
using namespace std;

/**
 * Init members and register apropriate listeners at the log handler.
 */
LoggerRequestFailPopularity::LoggerRequestFailPopularity()
{
	resetVars();

	LogHandler::getInstance()->addLogger(this, "clock_tick");
	LogHandler::getInstance()->addLogger(this, "node_requestFile");
}

/**
 * Opens file for writing and stores the Eos pointer
 */
void LoggerRequestFailPopularity::eos_simulate_start(void *eos)
{
	openFile(&m_fout, "requestfailpopularity.csv");
	m_fout << "Time Step";
	for(int i=0;i<m_partitions;i++){
		m_fout << ", Request Success Count Partition " << i << ", Request Fail Count Partition " << i;
	}
	m_fout << endl;

	m_eos = (Eos *)eos;
}

/**
 * Closes file
 */
void LoggerRequestFailPopularity::eos_simulate_stop(void *eos)
{
	m_fout.close();
}

/**
 * Writes the statistics for each tick
 */
void LoggerRequestFailPopularity::clock_tick(unsigned int time)
{
	// Write time step
	m_fout << time;

	// Write statistics
	for(int i=0;i<m_partitions;i++){
		m_fout << "," << m_countRequestSuccess[i] << "," << m_countRequestFail[i];
	}

	// Write end
	m_fout << endl;

	// Clear variables for next timestep
	resetVars();
}

/**
 * Checks if a request or insert call is a final success or final fail and saves it for writing on tick
 */
void LoggerRequestFailPopularity::node_requestFile(void *thisNode, void *params_in, bool result)
{
	NodeRequestFileParameters *params = (NodeRequestFileParameters *)params_in;

	// Check if it's an insert
	if(!params->m_insert){
		// Get the files index
		FileHandler *fileHandler = params->m_fileOwner->getFileHandler();
		int fileIndex = fileHandler->getIndexByFile(params->m_file);

		if(fileIndex >= 0){
			// Get the file popularity partition
			int popularityPartition = (int)(((double)fileIndex/(double)fileHandler->getFileCount())*(double)m_partitions);

			if(result){
				m_countRequestSuccess[popularityPartition]++;
			}
			else{
				m_countRequestFail[popularityPartition]++;
			}
		}
	}
}

/**
 * Resets all variables needed infor collecting a news set of data for a tick
 */
void LoggerRequestFailPopularity::resetVars()
{
	bzero(m_countRequestSuccess, m_partitions*sizeof(int));
	bzero(m_countRequestFail, m_partitions*sizeof(int));
}
